<template>
  <div class="p-6 max-w-7xl mx-auto">
    <h1 class="text-3xl font-bold text-gray-900 text-center mb-8">
      欢迎使用实验设备管理系统
    </h1>
    
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <!-- 设备总数 -->
      <div class="card hover:shadow-lg transition-shadow duration-200">
        <div class="card-body">
          <div class="flex items-center">
            <div class="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4">
              <ComputerDesktopIcon class="w-8 h-8 text-white" />
            </div>
            <div>
              <div class="text-3xl font-bold text-gray-900">{{ stats.equipmentCount }}</div>
              <div class="text-sm text-gray-600">设备总数</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 待审批申请 -->
      <div class="card hover:shadow-lg transition-shadow duration-200">
        <div class="card-body">
          <div class="flex items-center">
            <div class="w-16 h-16 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center mr-4">
              <DocumentTextIcon class="w-8 h-8 text-white" />
            </div>
            <div>
              <div class="text-3xl font-bold text-gray-900">{{ stats.pendingApplications }}</div>
              <div class="text-sm text-gray-600">待审批申请</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 借用中设备 -->
      <div class="card hover:shadow-lg transition-shadow duration-200">
        <div class="card-body">
          <div class="flex items-center">
            <div class="w-16 h-16 bg-gradient-to-br from-cyan-500 to-blue-500 rounded-full flex items-center justify-center mr-4">
              <ArchiveBoxIcon class="w-8 h-8 text-white" />
            </div>
            <div>
              <div class="text-3xl font-bold text-gray-900">{{ stats.borrowedEquipment }}</div>
              <div class="text-sm text-gray-600">借用中设备</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 维修中设备 -->
      <div class="card hover:shadow-lg transition-shadow duration-200">
        <div class="card-body">
          <div class="flex items-center">
            <div class="w-16 h-16 bg-gradient-to-br from-green-500 to-teal-500 rounded-full flex items-center justify-center mr-4">
              <WrenchScrewdriverIcon class="w-8 h-8 text-white" />
            </div>
            <div>
              <div class="text-3xl font-bold text-gray-900">{{ stats.repairingEquipment }}</div>
              <div class="text-sm text-gray-600">维修中设备</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 数据可视化图表 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- 设备状态分布 -->
      <div class="card">
        <div class="card-header">
          <h3 class="text-lg font-semibold text-gray-900">设备状态分布</h3>
        </div>
        <div class="card-body">
          <div class="h-80">
            <v-chart 
              class="w-full h-full" 
              :option="equipmentStatusOption" 
              autoresize
            />
          </div>
        </div>
      </div>
      
      <!-- 月度使用趋势 -->
      <div class="card">
        <div class="card-header">
          <h3 class="text-lg font-semibold text-gray-900">月度使用趋势</h3>
        </div>
        <div class="card-body">
          <div class="h-80">
            <v-chart 
              class="w-full h-full" 
              :option="usageTrendOption" 
              autoresize
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 最近申请 -->
      <div class="card">
        <div class="card-header">
          <h3 class="text-lg font-semibold text-gray-900">最近申请</h3>
          <button
            @click="$router.push('/equipment-application')"
            class="text-primary-600 hover:text-primary-700 text-sm font-medium"
          >
            查看全部
          </button>
        </div>
        <div class="card-body">
          <div class="overflow-x-auto">
            <table class="table">
              <thead>
                <tr>
                  <th>设备名称</th>
                  <th>申请人</th>
                  <th>状态</th>
                  <th>申请时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="app in recentApplications" :key="app.id">
                  <td>{{ app.name }}</td>
                  <td>{{ app.applicantName }}</td>
                  <td>
                    <span :class="getStatusClass(app.status)">
                      {{ getStatusText(app.status) }}
                    </span>
                  </td>
                  <td>{{ app.createTime }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      
      <!-- 最近借用 -->
      <div class="card">
        <div class="card-header">
          <h3 class="text-lg font-semibold text-gray-900">最近借用</h3>
          <button
            @click="$router.push('/equipment-borrow')"
            class="text-primary-600 hover:text-primary-700 text-sm font-medium"
          >
            查看全部
          </button>
        </div>
        <div class="card-body">
          <div class="overflow-x-auto">
            <table class="table">
              <thead>
                <tr>
                  <th>设备名称</th>
                  <th>借用人</th>
                  <th>借用时间</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="borrow in recentBorrows" :key="borrow.id">
                  <td>{{ borrow.equipmentName }}</td>
                  <td>{{ borrow.borrowerName }}</td>
                  <td>{{ borrow.borrowDate }}</td>
                  <td>
                    <span :class="getBorrowStatusClass(borrow.status)">
                      {{ getBorrowStatusText(borrow.status) }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import * as echarts from 'echarts'
import VChart from 'vue-echarts'
import {
  ComputerDesktopIcon,
  DocumentTextIcon,
  ArchiveBoxIcon,
  WrenchScrewdriverIcon
} from '@heroicons/vue/24/outline'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const userStore = useUserStore()

// 统计数据
const stats = ref({
  equipmentCount: 0,
  pendingApplications: 0,
  borrowedEquipment: 0,
  repairingEquipment: 0,
  normalEquipment: 0,
  scrappedEquipment: 0
})

// 最近申请
const recentApplications = ref([])

// 最近借用
const recentBorrows = ref([])

// 使用趋势数据
const usageTrendData = ref({
  months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  applicationCounts: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  borrowCounts: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  usageRates: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
})

// 获取状态样式类
const getStatusClass = (status) => {
  const statusClasses = {
    'PENDING': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800',
    'APPROVED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800',
    'REJECTED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800',
    'PURCHASED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800'
  }
  return statusClasses[status] || 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审批',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'PURCHASED': '已购买'
  }
  return statusMap[status] || status
}

// 获取借用状态样式类
const getBorrowStatusClass = (status) => {
  const statusClasses = {
    'BORROWED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800',
    'RETURNED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800',
    'OVERDUE': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800'
  }
  return statusClasses[status] || 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800'
}

// 获取借用状态文本
const getBorrowStatusText = (status) => {
  const statusMap = {
    'BORROWED': '借用中',
    'RETURNED': '已归还',
    'OVERDUE': '已超期'
  }
  return statusMap[status] || status
}

// 设备状态分布饼图配置
const equipmentStatusOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['正常', '借用中', '维修中', '已报废']
  },
  series: [
    {
      name: '设备状态',
      type: 'pie',
      radius: '50%',
      center: ['50%', '50%'],
      data: [
        { value: stats.value.normalEquipment || 0, name: '正常', itemStyle: { color: '#10B981' } },
        { value: stats.value.borrowedEquipment || 0, name: '借用中', itemStyle: { color: '#F59E0B' } },
        { value: stats.value.repairingEquipment || 0, name: '维修中', itemStyle: { color: '#EF4444' } },
        { value: stats.value.scrappedEquipment || 0, name: '已报废', itemStyle: { color: '#6B7280' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 月度使用趋势线图配置
const usageTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['设备使用率', '申请数量', '借用数量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: usageTrendData.value.months
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '设备使用率',
      type: 'line',
      data: usageTrendData.value.usageRates,
      smooth: true,
      itemStyle: { color: '#3B82F6' }
    },
    {
      name: '申请数量',
      type: 'line',
      data: usageTrendData.value.applicationCounts,
      smooth: true,
      itemStyle: { color: '#10B981' }
    },
    {
      name: '借用数量',
      type: 'line',
      data: usageTrendData.value.borrowCounts,
      smooth: true,
      itemStyle: { color: '#F59E0B' }
    }
  ]
}))

// 加载数据
const loadData = async () => {
  try {
    // 并行调用多个API获取数据
    const [equipmentStats, pendingApplications, applicationList, borrowList, usageTrend] = await Promise.all([
      request.get('/statistics/equipment'),
      request.get('/equipment-application/pending', { params: { pageNum: 1, pageSize: 1 } }),
      request.get('/equipment-application/list', { params: { pageNum: 1, pageSize: 5 } }),
      request.get('/equipment-borrow/list', { params: { pageNum: 1, pageSize: 5 } }),
      request.get('/statistics/equipment/trend')
    ])

    // 更新统计数据
    if (equipmentStats.data) {
      stats.value = {
        equipmentCount: equipmentStats.data.totalEquipment || 0,
        pendingApplications: pendingApplications.data?.total || 0,
        borrowedEquipment: equipmentStats.data.borrowedEquipment || 0,
        repairingEquipment: equipmentStats.data.repairingEquipment || 0,
        normalEquipment: equipmentStats.data.normalEquipment || 0,
        scrappedEquipment: equipmentStats.data.scrappedEquipment || 0
      }
    }

    // 更新最近申请数据
    if (applicationList.data && applicationList.data.records) {
      recentApplications.value = applicationList.data.records.map(app => ({
        id: app.id,
        name: app.equipmentName,
        applicantName: app.applicantName || '未知',
        status: app.status,
        createTime: app.createTime
      }))
    }

    // 更新最近借用数据
    if (borrowList.data && borrowList.data.records) {
      recentBorrows.value = borrowList.data.records.map(borrow => ({
        id: borrow.id,
        equipmentName: borrow.equipmentName,
        borrowerName: borrow.borrowerName,
        borrowDate: borrow.borrowTime,
        status: borrow.status
      }))
    }

    // 更新使用趋势数据
    if (usageTrend.data) {
      usageTrendData.value = {
        months: usageTrend.data.months || ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        applicationCounts: usageTrend.data.applicationCounts || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        borrowCounts: usageTrend.data.borrowCounts || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        usageRates: usageTrend.data.usageRates || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      }
    }

  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    // 如果API调用失败，使用默认值
    stats.value = {
      equipmentCount: 0,
      pendingApplications: 0,
      borrowedEquipment: 0,
      repairingEquipment: 0
    }
    recentApplications.value = []
    recentBorrows.value = []
  }
}

onMounted(() => {
  loadData()
})
</script>